#----------------------------------------------------------#
# Takes the path to the tables, computes the constants
# and sums for every n in the specified range after which 
# it makes input data for a graph builder. 
#----------------------------------------------------------#
from xlrd import open_workbook
import math

def evalZeroLoadProbability(n, _nu):
  p0 = 0
  for k in range(n):
    p0 += _nu**k / math.factorial(k)
  p0 += _nu**n / (math.factorial(n-1)*(n-_nu))
  p0 = 1 / p0
  return p0

def evalAvgIdleServersNum(n, _nu):
  p0 = evalZeroLoadProbability(n, _nu)
  N0 = 0
  for k in range(n):
    N0 += (n-k)*p0*_nu**k/math.factorial(k)
  return N0

def evalExpectedTimeOfStartOfService(n, _nu, _mu):
  return _nu**n*evalZeroLoadProbability(n, _nu) /\
         _mu*math.factorial(n+1)*(1-_nu/n)**2

def readTable(sheet):
    array = []
    for row_index in range(sheet.nrows):
      for col_index in range(sheet.ncols):
        val = sheet.cell(row_index,col_index).value
        if (val != ''):
          array.append(int(val))
    return array    

def getData( path, n):

  # open the tables and count the averages
  book = open_workbook(path)

  # query per time unit input array
  qptu  = readTable(book.sheet_by_index(0))

  # processed queries per time unit
  pptu  = readTable(book.sheet_by_index(1))
 
  # calculate the constants
  
  t_avg = sum(qptu)/len(qptu)
  _lambda = 1 / t_avg

  t_serv = sum(pptu)/len(pptu)
  _mu = 1 / t_serv

  _nu = _lambda / _mu

  data = {}# { n:Sumcost }

  for i in range(n):
    #Idle servers cost
    ISCost = 1000*evalAvgIdleServersNum(i+1, _nu)

    t_exp = evalExpectedTimeOfStartOfService(i+1, _nu, _mu)
    
    #Waiting queries cost
    WQCost = 8*t_exp**2 + 150*t_exp

    data[i+1] = ISCost + WQCost

  # write it to a file
  print(data)
